/*
 * @Author: 悦者生存 1002783067@qq.com
 * @Date: 2023-11-04 19:47:06
 * @LastEditors: 悦者生存 1002783067@qq.com
 * @LastEditTime: 2023-11-30 21:53:48
 * @FilePath: /client/src/utils/utils.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import md5 from 'md5';
export function getToken() {
  const jwt_token = localStorage.getItem('jwt_token');
  return jwt_token;
}

export function MD5(val: string, salt: string): Promise<string> {
  return new Promise((resolve) => {
    const result = md5(md5(val) + salt);
    resolve(result);
  });
}

// 随机数字
export function randomNum(m: number, n: number) {
  return Math.floor(Math.random() * (n - m + 1) + m);
}

// 随机颜色
export function randomColor() {
  return `rgb(${randomNum(0, 255)}, ${randomNum(0, 255)}, ${randomNum(
    0,
    255,
  )})`;
}

export const originalCharacter = [
  '1',
  '2',
  '3',
  '4',
  '5',
  '6',
  '7',
  '8',
  '9',
  'a',
  'b',
  'c',
  'd',
  'e',
  'f',
  'g',
  'h',
  'i',
  'j',
  'k',
  'l',
  'm',
  'n',
  'p',
  'q',
  'r',
  's',
  't',
  'u',
  'v',
  'w',
  'x',
  'y',
  'z',
];

// 验证密码
export const validatePassword = (
  rule: any,
  value: string,
): Promise<string | void> => {
  const oNumber = new RegExp(/\d/);
  const oLetter = new RegExp(/[a-zA-Z]/);
  const oSpecial = '.~!@#$%^&*()_+=-{}|:<>?,./[]-;\\"';
  const errorMessage = '密码不能小于6位，至少含字母、数字、特殊字符其中的2种！';
  return new Promise((resolve, reject) => {
    if (!value) {
      reject('密码不能为空');
    }

    if (value.length < 6) {
      reject(errorMessage);
    }

    try {
      [...value].forEach((val) => {
        if (
          !(
            oNumber.test(val) ||
            oLetter.test(val) ||
            oSpecial.indexOf(val) >= 0
          )
        ) {
          throw new Error();
        }
      });
    } catch (e) {
      reject(errorMessage);
    }

    const contain: boolean[] = [];

    [...value].forEach((val) => {
      if (oNumber.test(val)) {
        contain[0] = true;
      }
      if (oLetter.test(val)) {
        contain[1] = true;
      }
      if (oSpecial.indexOf(val) >= 0) {
        contain[2] = true;
      }
    });

    if (contain.filter((item) => item === true).length < 2) {
      reject(errorMessage);
    }
    resolve();
  });
};

// 验证密码确认
export const validateConfirmPassword = (
  rule: any,
  value: string,
  getFieldValue: (name: string) => any,
): Promise<string | void> => {
  return new Promise((resolve, reject) => {
    if (!value) {
      reject('确认密码不能为空');
    }
    if (getFieldValue('password') !== value) {
      reject('新密码与确认新密码不同！');
    }
    resolve();
  });
};

// 获取验证码
export const getValidateCode = (): string => {
  let str = '';
  for (let i = 0; i < 4; i++) {
    const temp = originalCharacter[randomNum(0, originalCharacter.length - 1)];
    str = `${str}${temp}`;
  }
  return str;
};
